<?php

namespace app\admin\controller\repository;

use app\common\controller\Backend;
use app\admin\logic\BacteriaLogic;


/**
 * Created by PhpStorm.
 * User: Orange
 * Date: 2018/4/26
 * Time: 9:59
 */

/**
 * 菌种管理
 * Class Bacteria
 * @package app\admin\controller\repository
 */
class Bacteria extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Bacteria');
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparamsNew();
            $filter = $this->request->get("filter", '');
            $filter = json_decode($filter, TRUE);
            $filter = $filter ? $filter : [];
            $category_ids = [];
            $map = [];
            $level = 0;
            foreach ($filter as $k => $v) {
                if (strstr($k, "category_id")) {
                    $category_ids[]= $v;
                    $current_level = model('Category')->where(array('id'=>$v))->value('current_level');
                    if($level < $current_level){
                        $level = $current_level;
                    }
                }
            }
            if(count($category_ids) > 0) {
                $map_where['category_id'] = ['in',$category_ids];
                $map_where['level'] = $level;
                $bacteria_list = model('BacteriaCategory')->where($map_where)->field('bacteria_id')->select();
                $bacteria_ids = [];
                foreach ($bacteria_list as $key => $value) {
                    $bacteria_ids[] = $value['bacteria_id'];
                }
                $map['id'] =['in',$bacteria_ids];
            }
            $total = $this->model
                ->where($map)
                ->where($where)
                ->where(array('is_use' => 1))
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($map)
                ->where($where)
                ->where(array('is_use' => 1))
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list, '$filter' => $category_ids);
            return json($result);
        }
        $map['is_use'] = 1;
        return $this->view->fetch();
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed $searchfields 快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparamsNew($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", "id");
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset", 0);
        $limit = $this->request->get("limit", 0);
        $filter = json_decode($filter, TRUE);
        $op = json_decode($op, TRUE);
        $filter = $filter ? $filter : [];
        $where = [];
        $tableName = '';
        if ($relationSearch) {
            if (!empty($this->model)) {
                $tableName = $this->model->getQuery()->getTable() . ".";
            }
            $sort = stripos($sort, ".") === false ? $tableName . $sort : $sort;
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$tableName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $tableName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        foreach ($filter as $k => $v) {
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (strstr($k, "category_id")) {
                continue;
            }
            if (stripos($k, ".") === false) {
                $k = $tableName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            switch ($sym) {
                case '=':
                case '!=':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FIND_IN_SET':
                    $where[] = "FIND_IN_SET('{$v}', `{$k}`)";
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr))
                        continue;
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } else if ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr))
                        continue;
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } else if ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
                    break;
                case 'LIKE':
                case 'LIKE %...%':
                    $where[] = [$k, 'LIKE', "%{$v}%"];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
        }
        $where = function ($query) use ($where) {
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit];
    }


    /**
     * 审核记录
     * @param string $ids
     * @return string|\think\response\Json
     */
    public function verify_log($ids = '')
    {
        if ($this->request->isAjax()) {
            $data = model('VerifyLog');
            $map['bacteria_id'] = $ids;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $data
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->count();
            $list = $data
                ->where($where)
                ->where($map)
                ->field(['password', 'salt', 'token'], true)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $key => &$value) {
                $nickName = model('Member')->where(array('id' => $value['member_id']))->value('name');
                $value['member_name'] = $nickName;
            }
            unset($value);
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->assignconfig('bacteria_id', $ids);
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->post('row/a');
            if ($data) {
                if (!check_num($data['amount'])) {
                    $this->error('请输入正确的数量');
                }
                if (!check_num($data['demand'])) {
                    $this->error('请输入正确的数量');
                }
                $bacteria = $this->model
                    ->where('chinese_name = :chinese_name OR the_latin_name = :the_latin_name', ['chinese_name' => $data['name'], 'the_latin_name' => $data['the_latin_name']])
                    ->where(array('is_use' => 1))
                    ->find();
                if ($bacteria) {
                    $this->error('菌种已存在');
                }

                $bacteriaData = array('chinese_name' => $data['name'],
                    'the_latin_name' => $data['the_latin_name'],
                    'demand' => $data['demand'],
                    'amount' => $data['amount']);
                $bacteria_obj = $this->model->create($bacteriaData);
                if ($bacteria_obj) {
                    $row['bacteria_id'] = $bacteria_obj['id'];
                    for ($level = 1; $level <= 7; $level++) {
                        $row['category_id'] = $data['category_id' . $level];
                        $row['category_name'] = $this->getCategoryChineseName($data['category_id' . $level]);
                        $row['english_name'] = $this->getCategoryEnglishName($data['category_id' . $level]);
                        $row['level'] = $level - 1;
                        model('BacteriaCategory')->create($row);
                    }
                    $this->success('添加成功');

                } else {
                    $this->error('添加失败');
                }
            }
            $this->error('添加失败');
        }
        return $this->view->fetch();
    }

    public function getCategoryChineseName($category_id)
    {
        $categoryChineseName = model('category')->where(array('id' => $category_id))->value('name');
        return $categoryChineseName;
    }

    public function getCategoryEnglishName($category_id)
    {
        $categoryEnglishName = model('category')->where(array('id' => $category_id))->value('english_name');
        return $categoryEnglishName;
    }

    public function edit($ids = '')
    {
        $row = $this->model->get(['id' => $ids]);
        $categoryData = model('BacteriaCategory')->where(array('bacteria_id' => $ids))->select();
        for ($level = 0; $level < 7; $level++) {
            $id = $level + 1;
            $row['category_id' . $id] = $categoryData[$level]['category_id'];
        }
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isAjax()) {
            $bacteriaData = $this->request->post('row/a');
            if ($bacteriaData) {
                for ($level = 0; $level < 7; $level++) {
                    $id = $level + 1;
                    if ($bacteriaData['category_id' . $id] != $categoryData[$level]['category_id']) {
                        $category['category_id'] = $bacteriaData['category_id' . $id];
                        $category['category_name'] = $this->getCategoryChineseName($bacteriaData['category_id' . $id]);
                        $category['english_name'] = $this->getCategoryEnglishName($bacteriaData['category_id' . $id]);
                        model('BacteriaCategory')->where(array('id' => $categoryData[$level]['id']))->update($category);
                    }
                }
                $data = array('chinese_name' => $bacteriaData['name'],
                    'the_latin_name' => $bacteriaData['the_latin_name'],
                    'demand' => $bacteriaData['demand'],
                    'amount' => $bacteriaData['amount']);
                $this->model->where(['id' => $ids])->update($data);
                $this->success('修改成功');
            }
            $this->error('修改失败');
        }


        $this->assignconfig('bacteria', $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public
    function del($ids = "")
    {
        if ($ids) {
            try {
                $this->model->where(array('id' => $ids))->update(array('is_use' => 0));
                $this->success('删除成功');
            } catch (Exception $e) {
                $this->error('删除失败');
            }
        }
        $this->error();
    }

    /**
     * 批量导入
     */
    public function import()
    {
        ignore_user_abort();
        set_time_limit(0);
        $file = $this->request->file('file');
        if ($file) {
            $fileInfo = $file->getInfo();
            $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
            $suffix = $suffix ? $suffix : 'file';
            if (!in_array($suffix, ['xls', 'xlsx'])) {
                $this->error('请上传Excel文件！');
            }
            $path = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'excel';
            if (!is_dir($path)) {
                mkdir($path, 0755, true);
            }
            $info = $file->move($path);
            if ($info) {
                $logic = new BacteriaLogic();
                $file_path = ROOT_PATH . 'public/uploads/excel/' . $info->getSaveName();
                $result = $logic->import($file_path);
                unlink($file_path);//删除文件
                $msg = '';
                $success = false;
                $rtnData = array();
                switch ($result['status']) {
                    case 0:
                        $msg = $result['msg'];
                        break;
                    case 1:
                        $success = true;
                        break;
                    case 2:
                        $msg = $result['msg'];
                        break;
                }
                if ($success) {
                    $this->success('导入成功！');
                } else {
                    $this->error($msg, '', $rtnData);
                }
            } else {
                // 上传失败获取错误信息
                $this->error($file->getError());
            }
        } else {
            $this->error('文件不存在！');
        }
    }
}